# clean_html -- from
#http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter

# ** NOTE: replace BeautifulSoup with lxml **

from BeautifulSoup import BeautifulSoup, NavigableString
import re

acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
  'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
  'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'font', 
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'label', 
  'legend', 'li', 'map', 'menu', 'ol', 'p', 'pre', 'q', 's', 'samp', 'small', 
  'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 
  'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var']

# style is not an acceptable attribute -- can be used to inject code.
acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', 
  'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
  'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
  'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'enctype', 
  'for', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 
  'label', 'lang', 'longdesc', 'maxlength', 'method', 'multiple', 'name', 
  'nohref', 'noshade', 'nowrap', 'prompt', 'rel', 'rev', 'rows', 'rowspan', 
  'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', 
  'summary', 'tabindex', 'target', 'title', 'type', 'usemap', 'valign', 
  'value', 'vspace', 'width']

def clean_html( fragment, okelements=acceptable_elements, okattributes=acceptable_attributes ):
    if fragment in [None, '']: return u''
    soup = BeautifulSoup( fragment.strip() )
    def cleanup( soup ):
        for tag in soup:
            if not isinstance( tag, NavigableString):
                if tag.name not in okelements:
                    tag.extract()
                else:
                    for attr in tag._getAttrMap().keys():
                        if attr not in okattributes:
                            del tag[attr]
                    cleanup( tag )
    cleanup( soup )
    return unicode( soup )
    
def clean_int_param(instr=None):
    """Given an input string, make sure it's an integer
    Examples:
    >>> clean_int('45')
    45
    >>> clean_int('45.83')
    45
    >>> clean_int('as45')
    45
    >>> clean_int('howdy')
    >>> 
    """
    if instr is not None:
        md = re.search("[0-9]+", instr)
        if md is not None:
            return md.group(0)
